﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;
using TransportAbstractionLibrary;
using TransportAbstractionLibrary.Layer;
using TransportAbstractionLibrary.TCP;
using TransportAbstractionLibrary.Common.BufferPool;

namespace ReceiveFile
{
    class Program
    {
        const int port = 123;
        static Socket socket;

        static void Main(string[] args)
        {
            acceptOneSocket();
            Console.ReadKey();
        }

        static void acceptOneSocket()
        {
            Socket listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            listenSocket.Bind(new IPEndPoint(IPAddress.Any, port));
            listenSocket.Listen(1);
            Console.WriteLine("Listening on port: " + port);
            SocketAsyncEventArgs args = new SocketAsyncEventArgs();
            args.Completed += accept_Compleated;
            if (!listenSocket.AcceptAsync(args))
            {
                accept_Compleated(listenSocket, args);
            }
        }

        static void accept_Compleated(object sender, SocketAsyncEventArgs e)
        {
            Console.WriteLine(e.SocketError.ToString());
            Console.WriteLine("Client connected!");
            socket = e.AcceptSocket;
            int bufferSize = 1024 * 128;
            BufferManager manager = new BufferManager(bufferSize * 2, 20);
            TCPProtocolBase protoclBase = new TCPProtocolBase(socket, manager);
            PackageLayer packageLayer = new PackageLayer(bufferSize);
            CompressionLayer compressionLayer = new CompressionLayer();
            FileWriter fileWriter = new FileWriter();
            protoclBase.Bind(packageLayer);
            packageLayer.Bind(compressionLayer);
            compressionLayer.Bind(fileWriter);
            protoclBase.Initialize();
        }
    }
}
